﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using StructureMap;
using StructureMap.Configuration.DSL;

namespace Crawler.Infrastructure
{
	public class IoCRegistrator
	{
		private static IContainer _container;
		private static bool _initialized = false;
		private static readonly object SyncLock = new object();

		public static void Register(IEnumerable<Registry> clientRegistries = null)
		{

			if (!_initialized)
				lock (SyncLock)
					if (!_initialized)
					{

						ObjectFactory.Initialize(
							c =>
							{
								if (clientRegistries != null)
									foreach (var clientRegistry in clientRegistries)
											c.AddRegistry(clientRegistry);
							});

						_container = ObjectFactory.Container;
						_container.Configure(x => x.For<IContainer>().Use(_container));

						foreach (var strap in _container.GetAllInstances<IBootstrap>())
							strap.Execute();


#if DEBUG
						ObjectFactory.Container.AssertConfigurationIsValid();
						ExtractInjectionReport();
#endif
						_initialized = true;

					}

		}

		public static void ExtractInjectionReport()
		{

			//Do not log into the bin folder as forces recompilation of the app(shadow copy)
			var directoryName = Path.Combine(AppDomain.CurrentDomain.GetData("APPBASE").ToString(), "DebugReports");

			if (!Directory.Exists(directoryName))
				Directory.CreateDirectory(directoryName);

			var fileName = Path.Combine(directoryName, "InjectionsReport.txt");
			var reportText = ObjectFactory.Container.WhatDoIHave();

			File.WriteAllText(fileName, reportText);

		}
	}
}
